<?php
class Admin_CatagoryController extends Zend_Controller_Action {
	private $_db;
	
	public function init() {
		/* Initialize action controller here */
		$this->_db = new Application_Model_DbTable_Catagory();
	}
	public function indexAction() {
		$catagories = $this->_db->fetchAll('del_flag = 0');
		$this->view->catagories = $catagories;
	}
	
	public function editAction(){
		$errors = array();
		$id = (int) $this->getRequest()->getParam('id');
		$catagory = $this->_db->find($id)->current();
		if ($this->getRequest()->isPost()) {
			$name = $this->getParam('name');
			if (! Zend_Validate::is ( $name, 'NotEmpty' )) {
				$errors [] = "'Tên hãng' không được để trống.";
			}
			
			if (count($errors) == 0) {
				$this->view->success = true;
				$where = $this->_db->getAdapter()->quoteInto('id = ?', $id);
				$this->_db->update(array('name' => $name), $where);
			} 
			$catagory->name = $this->getParam('name');
			
		}
		$this->view->errors = $errors;
		$this->view->catagory = $catagory;
		
	}
	
	public function addAction(){
		$errors = array();
		if ($this->getRequest()->isPost()) {
			$name = $this->getParam('name');
			if (! Zend_Validate::is ( $name, 'NotEmpty' )) {
				$errors [] = "'Tên hãng' không được để trống.";
			}
				
			if (count($errors) == 0) {
				$this->view->success = true;
				$this->_db->insert(array('name' => $name));
				$this->redirect('/admin/catagory');
			}
			$this->view->name = $this->getParam('name');
				
		}
		$this->view->errors = $errors;
		
	}
	
	public function deleteAction(){
		$id = $this->getParam('id');
		$where = $this->_db->getAdapter()->quoteInto('id = ?', $id);
		
		$this->_db->update(array('del_flag' => 1), $where);
		$this->redirect('/admin/catagory');
	}
}

